//
//  EmoticonPageCell.swift
//  emoticonKB
//
//  Created by mac on 16/3/20.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

let EmoticonBtnClickNotification = "EmoticonBtnClickNotification"

class EmoticonPageCell: UICollectionViewCell {
 
//    //设置一个调试属性
//    var indexPath: NSIndexPath? {
//    
//        didSet {
//            testLabel.text = "当前是第\(indexPath!.section)组第个\(indexPath!.item)cell"
//        }
//    }
    var emoticons: [Emoticons]? {
    
        didSet {
            
//遍历模型数据 然后依次给每个按钮赋值 可以将数组中的元素和对应的角标同时获取
            for(i,value) in emoticons!.enumerate() {
                
                let btn = emoticonBtns[i]

                //按钮绑定模型
                btn.emoticon = value

            }
        }
    }
    
    //表情按钮
//    var emoticonBtns = [UIButton]()
    var emoticonBtns = [EmoticonBtns]()
    
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 设置UI界面
    private func setupUI() {
        
//        contentView.addSubview(testLabel)
//        testLabel.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView.snp_edges)
//        }
        
        let leftMargin: CGFloat = 5
        let bottomMargin: CGFloat = 30
        let itemW = (UIScreen.mainScreen().bounds.width - 2 * leftMargin) / CGFloat(EmoticonColoumCount)
        let itemH = (self.bounds.height - bottomMargin) / CGFloat(EmoticonRowCount)
        for i in 0..<EmoticonCount {
        
            let btn = EmoticonBtns()
            
            //确定遍历的哪一行哪一列
            let col = i % EmoticonColoumCount
            let row = i / EmoticonColoumCount
            
            let x = CGFloat(col) * itemW + leftMargin
            let y = CGFloat(row) * itemH
            
            btn.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            btn.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
            btn.backgroundColor = UIColor.yellowColor()
            contentView.addSubview(btn)
            
            //添加点击表情事件 
            btn.addTarget(self, action: "emoticonClick:", forControlEvents: .TouchUpInside)
            
            //添加到数组中
            emoticonBtns.append(btn)
        }
    }
    
    @objc private func emoticonClick(btn: EmoticonBtns) {
    
//        print(btn.emoticon)
        
        //发送通知
    NSNotificationCenter.defaultCenter().postNotificationName(EmoticonBtnClickNotification, object: btn.emoticon)
    }
    
    
//    //MARK: 懒加载子视图 
//    private lazy var testLabel: UILabel = {
//    
//        let lb = UILabel()
//        lb.font = UIFont.systemFontOfSize(25)
//        lb.sizeToFit()
//        return lb
//    }()
    
}
